<template>
  <div class="app-container">
    <!-- 靠右的按钮 -->
    <page-tools>
      <template v-slot:right>
        <el-button type="primary" size="small" @click="addClick(1, '0')">添加权限</el-button>
      </template>
    </page-tools>
    <!-- 表格 -->
    <br>
    <el-card>
      <el-table border :data="tableData" row-key="id">
        <el-table-column label="权限名称" prop="name"/>
        <el-table-column align="center" label="权限标识" prop="code"/>
        <el-table-column align="center" label="权限描述" prop="description"/>
        <el-table-column align="center" label="操作">
          <template v-slot="{ row }">
            <el-button type="text" size="small" v-if="row.type === 1" @click="addClick(2, row.id)">添加</el-button>
            <el-button type="text" size="small" @click="editClick(row.id)">编辑</el-button>
            <el-button type="text" size="small" @click="delClick(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 新增或编辑权限弹层 -->
    <AddPermission ref="addPermission" :title="title" :dialogVisible.sync="dialogVisible" :type="type" :id="id"></AddPermission>
  </div>
</template>

<script>
import { getPermissionList, delPermission, getPermissionDetail } from '@/api/permission'
import { translateToTreeList } from '@/utils/index'
import AddPermission from './components/add-permission'
 
export default {
  name: 'PermissionIndex',
  components: {
    AddPermission
  },
  data() {
    return {
      tableData: [], // 表格数据
      title: '', // 弹层名称
      dialogVisible: false, // 控制弹层显示
      type: 0, // 权限类型
      id: '', // 权限id
    }
  },
  methods: {
    // 获取权限列表并转为树形
    async getPermissionList() {
      const data = await getPermissionList()
      this.tableData = translateToTreeList(data, '0')
    },
    // 添加操作
    addClick(type, id) {
      // type=1表示菜单访问权限，type=2表示按钮操作权限
      this.title = '新增权限'
      this.type = type
      this.id = id
      this.dialogVisible = true
    },
    // 编辑操作
    async editClick(id) {
      this.title = '编辑权限'
      this.id = id
      this.$refs.addPermission.form = await getPermissionDetail(id)
      this.dialogVisible = true
    },
    // 删除操作
    delClick(id) {
      this.$confirm('确定要删除该权限吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async () => {
        await delPermission(id)
        this.getPermissionList()
        this.$message.success('删除权限成功')
      }).catch(() => {})
    }
  },
  created() {
    this.getPermissionList()
  }
}
</script>
